package logic

import (
	"context"
	"fmt"
	"github.com/dtm-labs/client/dtmgrpc"
	"google.golang.org/protobuf/proto"
	"log"

	"github.com/google/uuid"
	"net/http"

	"month_zg6/api/internal/svc"
	"month_zg6/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderLogic {
	return &OrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderLogic) Order(req *types.OrderRequest) (resp *types.Response, err error) {
	return &types.Response{
		Code: http.StatusOK,
		Msg:  "",
		Data: map[string]interface{}{
			"GoodsID":         req.GoodsID,
			"GoodsName":       req.GoodsName,
			"GoodsPrice":      req.GoodsPrice,
			"GoodsNum":        req.GoodsNum,
			"UserID":          req.UserID,
			"ShippingAddress": req.ShippingAddress,
		},
	}, err
}

func AffairsDtm(Host string, Port int, rpcHost string, rpcPort int, proto, protoRollback string, payload proto.Message) bool {
	gid := uuid.NewString()
	saga := dtmgrpc.NewSagaGrpc(fmt.Sprintf("%s:%d", Host, Port), gid).
		Add(fmt.Sprintf("%s:%d/%s", rpcHost, rpcPort, proto), fmt.Sprintf("%s:%d/%s", rpcHost, rpcPort, protoRollback), payload)
	err := saga.Submit()
	if err != nil {
		log.Fatal(err)
		return false
	}
	return true
}
